package com.cn.wanxi.dao.impl;

import com.cn.wanxi.dao.INavDao;
import com.cn.wanxi.model.NavModel;
import com.cn.wanxi.util.GetSqlSession;
import com.cn.wanxi.util.JDBCUtils;
import redis.clients.jedis.Jedis;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class NavDaoImpl implements INavDao {
    private void clearNavRedis(){
        try {
            Jedis jedis = new Jedis();
            jedis.del("nav_id");
            jedis.del("nav_title");
            jedis.del("nav_href");
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @Override
    public int addNav(NavModel navModel) {
        clearNavRedis();
        return GetSqlSession.getSqlSession().insert("com.cn.wanxi.dao.INavDao.addNav",navModel);
    }

    @Override
    public int deleteNav(int id) {
        clearNavRedis();
        return GetSqlSession.getSqlSession().update("com.cn.wanxi.dao.INavDao.deleteNav",id);
    }

    @Override
    public int editNav(NavModel navModel) {
        clearNavRedis();
        return GetSqlSession.getSqlSession().update("com.cn.wanxi.dao.INavDao.editNav",navModel);
    }

    @Override
    public List<NavModel> getNavList() {
        return GetSqlSession.getSqlSession().selectList("com.cn.wanxi.dao.INavDao.getNavList");
    }

    @Override
    public NavModel getNav(int id) {
        return GetSqlSession.getSqlSession().selectOne("com.cn.wanxi.dao.INavDao.getNav",id);
    }

    @Override
    public List<NavModel> getNavs(Map<String,Object> map) {
        return GetSqlSession.getSqlSession().selectList("com.cn.wanxi.dao.INavDao.getNavs",map);
    }

    @Override
    public long getNavCount(Map<String,Object> map) {
        return GetSqlSession.getSqlSession().selectOne("com.cn.wanxi.dao.INavDao.getNavCount",map);
    }

    @Override
    public int updateShow(NavModel nav) {
        clearNavRedis();
        return GetSqlSession.getSqlSession().update("com.cn.wanxi.dao.INavDao.updateShow",nav);
    }


    @Override
    public List<NavModel> getNavListByRedis() {
        Jedis jedis = new Jedis();
        List<NavModel> list = new ArrayList<>();
        List<String> navId = jedis.lrange("nav_id", 0, -1);
        for (int i = 0; i < navId.size(); i++) {
            NavModel navModel = new NavModel();
            navModel.setId(Integer.valueOf(navId.get(i)));
            navModel.setTitle(jedis.lindex("nav_title", i));
            navModel.setHref(jedis.lindex("nav_href", i));
            list.add(navModel);
        }
        return list;
    }

    @Override
    public void setNavListInRedis(List<NavModel> navList) {
        Jedis jedis = new Jedis();
        for (NavModel nav : navList) {
            jedis.rpush("nav_id", String.valueOf(nav.getId()));
            jedis.rpush("nav_title", nav.getTitle());
            jedis.rpush("nav_href", nav.getHref());
        }
    }
}
